package com.ifacebox.client.tools;

import com.ifacebox.client.tools.utils.ThreadUtils;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;

import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;

/**
 * @author znn
 */
public class FaceLuckDrawCountdownDialog extends JDialog {
    private static final long serialVersionUID = 1L;
    private final Frame frame;
    private final FaceLuckDrawConfig faceLuckDrawConfig;
    private JLabel faceLuckDrawCountdown;
    private int x, y;

    public FaceLuckDrawCountdownDialog(Frame frame, FaceLuckDrawConfig faceLuckDrawConfig) {
        super(frame);
        this.frame = frame;
        this.faceLuckDrawConfig = faceLuckDrawConfig;
        super.setTitle(frame.getTitle());
        super.setIconImage(frame.getIconImage());
        super.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        super.addMouseListener(new MouseAdapter() {
            @Override
            public void mousePressed(MouseEvent e) {
                x = e.getX();
                y = e.getY();
            }
        });
        super.addMouseMotionListener(new MouseMotionAdapter() {
            @Override
            public void mouseDragged(MouseEvent e) {
                setLocation(e.getXOnScreen() - x, e.getYOnScreen() - y);
            }
        });
        super.setUndecorated(true);
        super.setBackground(new Color(0, 0, 0, 0));
        this.initComponent();
        super.add(faceLuckDrawCountdown, BorderLayout.CENTER);
        super.pack();
        super.setResizable(false);
        super.setLocationRelativeTo(frame);
    }

    public void faceLuckDrawCountdown(CountdownCallback callback, int faceLuckWin) {
        if (super.isVisible()) {
            return;
        }
        super.setLocationRelativeTo(frame);
        super.setVisible(true);
        ThreadUtils.run(() -> {
            faceLuckDrawCountdown.setText("");
            for (int i = 0; i < faceLuckDrawConfig.getFaceLuckDrawCountdown(); i++) {
                faceLuckDrawCountdown.setText(String.valueOf(faceLuckDrawConfig.getFaceLuckDrawCountdown() - i));
                ThreadUtils.sleepOneSecond();
            }
            callback.onLuckDrawSelection(faceLuckWin);
            setVisible(false);
        });
    }

    public void initComponent() {
        faceLuckDrawCountdown = new JLabel(String.valueOf(faceLuckDrawConfig.getFaceLuckDrawCountdown()), JLabel.CENTER);
        faceLuckDrawCountdown.setFont(new Font("", Font.BOLD, 12 * 24));
        faceLuckDrawCountdown.setForeground(Color.RED);
    }

    public interface CountdownCallback {
        /**
         * 抽奖
         *
         * @param faceLuckWin 数量
         */
        void onLuckDrawSelection(int faceLuckWin);
    }

}
